import { Component, OnInit, Input,Output, EventEmitter } from '@angular/core';
import { TreeModule, TreeNode } from 'primeng/primeng';
import { Service } from '../../../server/server';
import { TreeService } from 'app/public/serve/tree/tree.service';
import { HintsService } from 'app/public/serve/hints/hints.service';
import { productTypeToken } from '../token.data';
import {CudTableService} from '../../../public/serve/cud-table/cud-table.service';

@Component({
  selector: 'app-product-type-tree',
  templateUrl: './product-type-tree.component.html',
  styleUrls: ['./product-type-tree.component.css']
})

export class ProductTypeTreeComponent implements OnInit {

  @Output() tree       = new EventEmitter<void>();
  @Output() nodeSelect = new EventEmitter<void>();
  public productTypeCurrentId : any;
  @Input() showTitle: any;
  treeData      : TreeNode[];
  selectedFile  : TreeNode[]; 

  constructor(
    private treeService: TreeService,
    private hintsService: HintsService,
    private server:Service,
    private tableListService: CudTableService
  ) { }

  ngOnInit() {
    this._tree();
  }

  /**
   * 选中的节点
   * @param event 
   * @param id 
   */
  _nodeSelect(event, id) {
    this.productTypeCurrentId = event.node;
    if ((event.node.name as string).indexOf("已禁用") > -1) {
      // ipRule.isDisable = true;
    } else {
      // ipRule.isDisable = false;
    }

    // ipRule.tree.institutionName = event.node.institutionName;
    // ipRule.tree.institutionId   = event.node.institutionId;
    // ipRule.tree.parentId        = event.node.parentId;
    this.treeTopActive = false;
    this.nodeSelect.emit(this.productTypeCurrentId);
  }

  /**
   * 树状图
   */ 
  _tree() {
      let url = this.server.baseUrl + 'service/producttype/getProParentInfos';
      this.tableListService.getRequest(url).then((data: any) => {
          if(data.result_code == '0000') {
              this.treeData = data.result;
              this.treeData = this.processTreeData(this.treeData, 'categoryId', 'name');
              //默认加载第一个
              this.productTypeCurrentId = data.result[0];

              // 默认选中第一个节点（注释部分为：展开第一个节点）
              if(this.showTitle != 0){
                this.selectedFile = [this.treeData[0]];
                this.nodeSelect.emit(this.productTypeCurrentId);
              }
              this.tree.emit();
              return
          }else {
              this.hintsService.messages(data.message, data.result_code);
          }
      }).catch();
  }


  public processTreeData(list: Array<any>, id, name): Array<any> {
    return this.getTreeChildren(list, '0', id, name);
  }

  public getTreeChildren(list: Array<any>, parentid: string, id?: string, name?: string): Array<any> {
      let idKey: string = id;
      let labelKey: string = name;
      let result: Array<any> = [];
      for (let item of list) {
          if (item.parentid == parentid) {
            this.fillCSTreeNode(item, item[idKey], item[labelKey]);
              let children = this.getTreeChildren(list, item[idKey], id, name);
              if (children && children.length > 0) {
                  item.children = children;
                  item.leaf = false;
                  item.expanded = true;
              } else {
                  item.leaf = true;
                  item.expanded = false;
              }
              result.push(item);
          }
      }
      return result;
  }

  public fillCSTreeNode(node: any, data: string, label: string): void {
      node.data = data;
      node.label = label;
      node.expandedIcon = 'fa-minus-square-o';
      node.collapsedIcon = 'fa-plus-square-o';
  }

  /**
   * 展开所有树节点
   */
  private _expandAll() {
    this.treeData.forEach(node => {
      this.expandRecursive(node, true);
    });
  }

  // 递归
  private expandRecursive(node: TreeNode, isExpand: boolean) {
    node.expanded = isExpand;
    if (node.hasOwnProperty('childProductTypeVoList')) {
      node.children = node['childProductTypeVoList'];
      node.children.forEach(childNode => {
        this.expandRecursive(childNode, false);
      });
    }
  }

  /**
   * 最上级
   * @param id
   */ 
  public treeTopActive:boolean = true;
  toMogami(id) {
    this.nodeSelect.emit(id);
    this.selectedFile = []
    this.treeTopActive = true;
  }

}
